from decimal import Decimal
from flask import Flask, request, render_template, redirect, session, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
import os
from connect_sql import con_sql
import pymysql
import datetime


app = Flask(__name__)
app.secret_key = 'secret_key' 

template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../前端/templates')
app.template_folder = template_dir
# print(f"模板文件夹路径：{template_dir}")  # 打印路径，确认是否正确

def get_user_card_info(customer_id):
    try:
        sql = "SELECT * FROM cardinfo WHERE customerID = %s"
        cursor_ans = con_sql(sql, (customer_id,))
        card_info_list = cursor_ans.fetchall()
        # print("查询结果:", card_info_list)
        
        result = []
        for row in card_info_list:
            # row 是字典类型，直接用字段名访问
            open_date = row["openDate"].strftime('%Y-%m-%d %H:%M:%S') \
                if isinstance(row["openDate"], datetime.datetime) else row["openDate"]
            
            card_dict = {
                "cardID": row["cardID"],
                "curID": row["curID"],
                "savingID": row["savingID"],
                "openDate": open_date,
                "openMoney": float(row["openMoney"]) if isinstance(row["openMoney"], Decimal) else row["openMoney"],
                "balance": float(row["balance"]) if isinstance(row["balance"], Decimal) else row["balance"],
                "pass": row["pass"],
                "IsReportLoss": row["IsReportLoss"],
                "customerID": row["customerID"]
            }
            result.append(card_dict)
        return result
    
    except Exception as e:
        print(f"查询卡信息失败: {customer_id}，具体异常: {str(e)}")
        return []

# @app.route("/")
# def index():
#     return render_template('1.html')

# @app.route("/login", methods=["post"])
# def login():
#     name = request.form.get("username")
#     pwd = request.form.get("password")
#     # print(f"收到数据：name={name}, pwd={pwd}")
#     return f"{name},{pwd}"

@app.route("/")
def bank_homepage():
    return render_template('bank_home.html')

@app.route("/register")
def register_homepage():
    return render_template('register_home.html')

@app.route("/personal")
def personal_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    # print(session)
    # 重新查询余额（关键新增代码）
    customerid = user_data['customerid']
    code_sum = "SELECT SUM(balance) AS total_balance FROM cardinfo WHERE customerID = %s"
    cursor_sum = con_sql(code_sum, (customerid))
    cursor_select_sum = cursor_sum.fetchone()
    new_balance = cursor_select_sum.get('total_balance') or 0
    
    # 更新 Session 中的余额
    user_data['balance'] = str(new_balance)
    session['user_data'] = user_data
    return render_template('personal_home.html', user=user_data)

@app.route("/account")
def account_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('account_home.html', user=user_data)

@app.route("/trade")
def trade_homepage():
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    customer_id = user_data.get("customerid")  #确认 user_data 里有没有这个字段，没有的话从查询结果取
    card_info_list = get_user_card_info(customer_id)# 查询卡信息
    session['user_data']['card_info'] = card_info_list # 将卡信息存入 session
    user_data = session.get('user_data')# 从 Session 中获取用户信息
    # print(user_data)
    if not user_data:# 如果 Session 中没有用户信息，说明未登录
        return redirect("/")  # 跳转到登录页
    return render_template('trade_home.html', user=user_data)

@app.route('/savemoney')
def savemoney_homepage():
    return render_template('savemoney_home.html')

@app.route('/flow')
def flow_homepage():
    return render_template('flow_home.html')

@app.route('/changeinfo')
def changeinfo_homepage():
    return render_template('changeinfo_home.html')

@app.route('/loss')
def loss_homepage():
    return render_template('loss_home.html')

@app.route("/login", methods=["post"])
def login():
    error_msg=None

    id = request.form.get("login-username")
    pwd = request.form.get("login-password")
    # print(f"收到数据：id={id}, pwd={pwd}")
    code = "SELECT * FROM userinfo WHERE PID = %s OR telephone = %s"# % (id,id)
    cursor_ans = con_sql(code,(id,id))
    cursor_select = cursor_ans.fetchall()
    if len(cursor_select)>0:
        if pwd == cursor_select[0]['password']:#登录成功
            customerid = cursor_select[0]['customerID']#获取登录用户的customerID
            code_sum = "SELECT SUM(balance) AS total_balance FROM cardinfo WHERE customerID = %s"# % (customerid)
            cursor_sum = con_sql(code_sum,(customerid))
            cursor_select_sum = cursor_sum.fetchone()
            total_balance = cursor_select_sum.get('total_balance')
            session['user_data']={
                "name": cursor_select[0]['customerName'],
                "balance": total_balance if total_balance is not None else 0,  # 处理无记录的情况
                "pid": cursor_select[0]['PID'],
                "customerid": customerid
            }
            return redirect("/personal")
        else:#登录失败
            return """
            <html>
            <body>
                <script>
                    alert('用户名或密码错误，请重新输入！');
                    window.history.back();  // 回到上一页（登录页面）
                </script>
            </body>
            </html>
            """
    else:
        return """
        <html>
        <body>
            <script>
                alert('用户名或密码错误，请重新输入！');
                window.history.back();  // 回到上一页（登录页面）
            </script>
        </body>
        </html>
        """

@app.route("/register", methods=["post"])
def register():
    username = request.form.get("register-username")
    phone = request.form.get("register-phone")
    idcard = request.form.get("register-idcard")
    address = request.form.get("register-address")
    password = request.form.get("register-password")
    confirm_password = request.form.get("register-confirm-password")
    if len(password) < 6:
        return """
            <html>
            <body>
                <script>
                    alert('密码不符合规范，请重新注册！');
                    window.history.back();  // 回到上一页（注册页面）
                </script>
            </body>
            </html>
            """
    if password != confirm_password:
        return """
            <html>
            <body>
                <script>
                    alert('两次输入的密码不一致，请重新注册！');
                    window.history.back();  // 回到上一页（注册页面）
                </script>
            </body>
            </html>
            """
    # print(f"收到数据：username={username},phone={phone},idcard={idcard},address={address},password={password},confirm_password={confirm_password}")
    code0 = "SELECT * FROM userinfo WHERE PID = %s OR telephone = %s"# % (idcard,phone)
    cursor_ans0 = con_sql(code0,(idcard,phone))
    cursor_select0 = cursor_ans0.fetchall()
    if len(cursor_select0) > 0:#已经存在该用户
        return """
            <html>
            <body>
                <script>
                    alert('此身份证或手机号已拥有账户！');
                    window.history.back();  // 回到上一页（注册页面）
                </script>
            </body>
            </html>
            """
    else:#注册成功
        code = "INSERT INTO userInfo (customerName, PID, telephone, address, password) VALUES (%s, %s, %s, %s, %s)"# % (username, idcard, phone, address, password)
        cursor_ans = con_sql(code,(username, idcard, phone, address, password))
        return """
        <html>
        <body>
            <script>
                alert('注册成功！');
                window.location.href = '/';// 跳转到登录界面
            </script>
        </body>
        </html>
        """

@app.route('/trade', methods=['POST'])
def trade():
    # 获取表单数据
    payee_name = request.form.get('payee_name')
    payee_cardid = request.form.get('payee_cardid')
    payee_phone = request.form.get('payee_phone')
    payer_card = request.form.get('selected_card')# 获取隐藏字段中的卡号
    payer_money = request.form.get('payer_money')
    payer_password = request.form.get('payer_password')
    # print(payer_card)
    # return payer_card
    # print(f"payee_phone:{payee_phone}")
    if  not payee_phone:
        code = "SELECT * FROM cardinfo WHERE cardID = %s"
        cursor_ans = con_sql(code,(payer_card))
        cursor_select = cursor_ans.fetchall()
    else:
        code = "SELECT cardinfo.* FROM cardinfo JOIN userinfo ON cardinfo.customerID = userinfo.customerID WHERE userinfo.telephone = %s AND cardinfo.savingID = 1"
        cursor_ans = con_sql(code,(payee_phone))
        cursor_select = cursor_ans.fetchall()
    if len(cursor_select) > 0:
        if payer_password == cursor_select[0]['pass']:#密码正确
            # code_trade_payer = "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)"
            # code_trade_payee = "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)"
            # con_sql(code_trade_payer,('NOW()','转账',payer_card,payer_money,'转至{payee_cardid},金额:{payer_money}'))
            # con_sql(code_trade_payer,('NOW()','收账',payer_card,payer_money,'接收来自{payer_card}的转账'))
            trade_remark_payer = f"转至{payee_cardid},金额:{payer_money}"
            trade_remark_payee = f"接收来自{payer_card}的转账"
            result1 = con_sql(
                "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)",
                (datetime.datetime.now(), '转账', payer_card, payer_money, trade_remark_payer)
            )
            result2 = con_sql(
                "INSERT INTO tradeinfo (tradeDate, tradeType, cardID, tradeMoney, remark) VALUES (%s, %s, %s, %s, %s)",
                (datetime.datetime.now(), '收账', payee_cardid, payer_money, trade_remark_payee)
            )

            if isinstance(result1, tuple) and len(result1) == 2:
                error_type, error_msg = result1
                # 将异常值存入字符串
                error_str = f"数据库错误类型: {error_type}, 错误信息: {error_msg}"
                print(error_str)  # 这里可以根据需求，比如返回给前端、记录日志等
                return """
                <html>
                <body>
                    <script>
                        alert('转账失败,请检查余额是否充足并确认转入转出卡是否被冻结');
                        window.location.href = '/personal';
                    </script>
                </body>
                </html>
                """

            if isinstance(result2, tuple) and len(result2) == 2:
                error_type, error_msg = result2
                # 将异常值存入字符串
                error_str = f"数据库错误类型: {error_type}, 错误信息: {error_msg}"
                print(error_str)  # 这里可以根据需求，比如返回给前端、记录日志等
                return f"""
                <html>
                <body>
                    <script>
                        alert('转账失败,请检查余额是否充足并确认转入转出卡是否被冻结');
                        window.location.href = '/personal';
                    </script>
                </body>
                </html>
                """

            return"""
            <html>
            <body>
                <script>
                    alert('转账成功！');
                    window.location.href = 'personal'// 回到登录页面
                </script>
            </body>
            </html>
            """
        else:
            return"""
            <html>
            <body>
                <script>
                    alert('密码错误！');
                    window.location.href = 'personal'// 回到登录页面
                </script>
            </body>
            </html>
            """
    else:
        return"""
        <html>
        <body>
            <script>
                alert('错误！没有银行卡！请重新登录！');
                window.location.href = '/'// 回到登录页面
            </script>
        </body>
        </html>
        """

if __name__ == '__main__':
    app.run(debug=True)